<?php
/**
 * Created by PhpStorm.
 * User: Sergey
 * Date: 14.03.14
 * Time: 18:53
 */

include_once BASE_DQ_PLUGIN_PATH . "classes/Config.php";
include_once BASE_DQ_PLUGIN_PATH . "classes/ConnectionFactory.php";
include_once BASE_DQ_PLUGIN_PATH . "classes/Group.php";

class GroupDao extends ConnectionFactory
{
    /**
     * @param $row
     * @return Group
     */
    public function fetch($row)
    {
        try {
            $group = new Group();
            $group->id = $row->id;
            $group->name = $row->name;
            return $group;
        } catch (Exception $ex) {
            return null;
        }
    }

    /**
     * @return Group array
     */
    public function getAll()
    {
        $result = $this->getAllRows(Config::get()->getGroupsTableName());
        $groups = array();
        foreach ($result as $row) {
            $groups[] = $this->fetch($row);
        }
        return $groups;
    }

    /**
     * @param int $id
     * @return Group|null
     */
    public function getById($id)
    {
        $row = $this->getRow(Config::get()->getGroupsTableName(), $id);
        return $this->fetch($row);
    }

    /**
     * @param Group $group
     */
    public function add(Group $group)
    {
        global $wpdb;
        $wpdb->insert(
            Config::get()->getGroupsTableName(),
            array("name" => $group->name),
            array("%s")
        );
    }

    /**
     * @param Group $group
     */
    public function edit(Group $group)
    {
        global $wpdb;
        $wpdb->update(
            Config::get()->getGroupsTableName(),
            array("name" => $group->name),
            array("id" => $group->id),
            array("%s"),
            array("%d")
        );
    }

    /**
     * @param int $id
     */
    public function remove($id)
    {
        $this->removeRow(
            Config::get()->getGroupsTableName(),
            $id
        );
    }
}